<template>
  <div class="app-container">
    <!-- 搜索工作栏 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
      <el-form-item label="状态:" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择" clearable @keyup.enter.native="handleQuery" size="small">
          <el-option label="未开启" value="0"></el-option>
          <el-option label="开启" value="1"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="优惠券名称:" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入优惠券名称" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作工具栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="openForm(undefined)"
                   v-hasPermi="['discount:store-coupon:create']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport" :loading="exportLoading"
                   v-hasPermi="['discount:store-coupon:export']">导出</el-button>
      </el-col>
              <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

            <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
            <el-table-column label="编号" align="left" prop="id" />
      <el-table-column label="优惠券名称" align="left" prop="name" />
      <el-table-column label="优惠券面值" align="left" prop="money" />
              <el-table-column label="发布数量" align="left" prop="total">
                <template v-slot="scope">
                  <span v-if="scope.row.total === 0">不限量</span>
<!--                  <span v-else>(发布:{{ scope.row.total }})(剩余: {{ scope.row.lastTotal }})</span>-->
                  <span style="color: blue">发布:{{ scope.row.total }}</span><br />
                  <span style="color: red">剩余:{{ scope.row.lastTotal }}</span>
                </template>
              </el-table-column>
      <el-table-column label="类型" align="left" prop="useType">
        <template v-slot="scope">
          <el-tag v-if="scope.row.useType === 1">通用券</el-tag>
          <el-tag v-if="scope.row.useType === 2">商品券</el-tag>
          <el-tag v-if="scope.row.useType === 3">品类券</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="领取日期" align="left" prop="receiveStartTime" width="350">
        <template v-slot="scope">
          <span v-if="scope.row.receiveStartTime != null && scope.row.receiveEndTime != null">{{ parseTime(scope.row.receiveStartTime) }}-{{ parseTime(scope.row.receiveEndTime) }}</span>
          <span v-else>不限时</span>
        </template>
      </el-table-column>
      <el-table-column label="使用时间" align="left" prop="useStartTime" width="350">
        <template v-slot="scope">
          <span v-if="scope.row.useStartTime != null && scope.row.useEndTime != null">{{ parseTime(scope.row.useStartTime) }}-{{ parseTime(scope.row.useEndTime) }}</span>
          <span v-else>{{ scope.row.day }}天</span>
        </template>
      </el-table-column>
<!--      <el-table-column label="天数" align="center" prop="day" />-->
      <el-table-column label="领取方式" align="left" prop="type">
        <template v-slot="scope">
          <el-tag v-if="scope.row.type === 1">手动领取</el-tag>
          <el-tag v-if="scope.row.type === 2">新人卷</el-tag>
          <el-tag v-if="scope.row.type === 3">赠送券</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="left" prop="status" width="100">
        <template v-slot="scope">
          <el-switch
            v-model="scope.row.status"
            :active-value="1"
            :inactive-value="0"
            active-text="开"
            inactive-text="关"
            @change="handleStatusChange(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="right" class-name="small-padding fixed-width" fixed="right">
        <template v-slot="scope">
          <div style="text-align: right;">
            <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                       v-hasPermi="['discount:store-coupon:delete']">删除</el-button>
            <el-button size="mini" type="text" @click="openReceiveRecord(scope.row)">领取记录</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNo" :limit.sync="queryParams.pageSize"
                @pagination="getList"/>
    <!-- 对话框(添加 / 修改) -->
    <StoreCouponForm ref="formRef" @success="getList" @productSelect="handleProductSelect" />

    <el-dialog title="领取记录" :visible.sync="receiveRecordVisible" width="600px">
      <el-table :data="receiveRecordList" v-loading="receiveRecordLoading" style="width: 100%">
        <el-table-column label="用户头像" width="80">
          <template v-slot="scope">
            <el-avatar :src="scope.row.avatar" />
          </template>
        </el-table-column>
        <el-table-column label="用户昵称" prop="nickname" />
        <el-table-column label="领取时间" prop="createTime" />
      </el-table>
    </el-dialog>
    </div>
</template>

<script>
import * as StoreCouponApi from '@/api/discount/storecoupon';
import StoreCouponForm from './StoreCouponForm.vue';
import * as CategoryApi from '@/api/store/category';
import * as StoreCouponUserApi from '@/api/discount/storecouponuser';

export default {
  name: "StoreCoupon",
  components: {
          StoreCouponForm,
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 显示搜索条件
      showSearch: true,
              // 总条数
        total: 0,
      // 优惠券列表
      list: [],
      // 是否展开，默认全部展开
      isExpandAll: true,
      // 重新渲染表格状态
      refreshTable: true,
      // 选中行
      currentRow: {},
      // 查询参数
      queryParams: {
                    pageNo: 1,
            pageSize: 10,
        name: null,
        status:null,
      },
      selectedProducts: [], // 多选商品数组
      categoryOption: [], // 分类级联数据
      selectedCategoryIds: [], // 选中的分类id数组
      receiveRecordVisible: false,
      receiveRecordList: [],
      receiveRecordLoading: false,
            };
  },
  created() {
    this.getCategoryList();
    this.getList();
  },
  methods: {
    /** 查询列表 */
    async getList() {
      try {
      this.loading = true;
              const res = await StoreCouponApi.getStoreCouponPage(this.queryParams);
        this.list = res.data.list;
        this.total = res.data.total;
      } finally {
        this.loading = false;
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 添加/修改操作 */
    openForm(id) {
      this.$refs["formRef"].open(id);
    },
    /** 删除按钮操作 */
    async handleDelete(row) {
      const id = row.id;
      await this.$modal.confirm('是否确认删除优惠券编号为"' + id + '"的数据项?')
      try {
       await StoreCouponApi.deleteStoreCoupon(id);
       await this.getList();
       this.$modal.msgSuccess("删除成功");
      } catch {}
    },
    /** 导出按钮操作 */
    async handleExport() {
      await this.$modal.confirm('是否确认导出所有优惠券数据项?');
      try {
        this.exportLoading = true;
        const data = await StoreCouponApi.exportStoreCouponExcel(this.queryParams);
        this.$download.excel(data, '优惠券.xls');
      } catch {
      } finally {
        this.exportLoading = false;
      }
    },
    async handleStatusChange(row) {
      try {
        await StoreCouponApi.updateStoreCouponStatus(row.id, row.status);
        this.$modal.msgSuccess("状态更新成功");
        this.getList();
      } catch {
        this.$modal.msgError("状态更新失败");
        row.status = row.status === 0 ? 1 : 0;
      }
    },
    handleProductSelect(products) {
      if (products && products.length > 0) {
        this.selectedProducts = products;
        this.formData.productIds = products.map(item => item.id); // 提交时用
      } else {
        this.selectedProducts = [];
        this.formData.productIds = [];
      }
    },
    async getCategoryList() {
      const res = await CategoryApi.getCategoryList({ status: 1 });
      if (res.code === 0) {
        this.categoryOption = this.buildCascaderOptions(res.data);
      }
    },
    buildCascaderOptions(list) {
      const rootCategories = list.filter((category) => category.pid === 0);
      const buildChildren = (parentId, level = 1) => {
        const children = list
          .filter((category) => category.pid === parentId)
          .map((category) => {
            const option = {
              value: category.id,
              label: category.name,
            };
            if (level < 3) {
              const childOptions = buildChildren(category.id, level + 1);
              if (childOptions && childOptions.length > 0) {
                option.children = childOptions;
              }
            }
            return option;
          });
        return children;
      };
      return rootCategories.map((category) => {
        const option = {
          value: category.id,
          label: category.name,
        };
        const children = buildChildren(category.id, 1);
        if (children && children.length > 0) {
          option.children = children;
        }
        return option;
      });
    },
    handleCategoryChange(ids) {
      // 只取最后一级分类id
      this.formData.categoryId = ids.length ? ids[ids.length - 1] : null;
    },
async openReceiveRecord(row) {
  this.receiveRecordVisible = true;
  this.receiveRecordLoading = true;
  try {
    const res = await StoreCouponUserApi.getuserCoupon({
      couponId: row.id,
      pageNo: 1,
      pageSize: 100,
    });
    if (res.code === 0) {
      // 兼容后端返回 { list: [...] } 或直接返回数组
      this.receiveRecordList = Array.isArray(res.data)
        ? res.data
        : (res.data.list || []);
    } else {
      this.receiveRecordList = [];
    }
  } finally {
    this.receiveRecordLoading = false;
  }
}
  },
};
</script>
